package org.dolphin.dao.impl;

import java.io.Serializable;
import java.util.List;
import org.dolphin.base.bean.FlatCustomerVO;
import org.dolphin.dao.CustomerDao;
import org.dolphin.dao.util.SessionHelper;
import org.dolphin.entity.customer.Customer;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.ProjectionList;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.hibernate.sql.JoinType;
import org.hibernate.transform.AliasToBeanResultTransformer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

@Repository(value = "customerDao")
public class CustomerDaoImpl implements CustomerDao {
  @Autowired(required = true)
  private SessionFactory sessionFactory;

  protected DetachedCriteria buildCustomerCriteria() {
    DetachedCriteria dc = DetachedCriteria.forClass(Customer.class);
    return dc;
  }

  @SuppressWarnings("unchecked")
  @Override
  public Customer fetchCustomer(Serializable id, boolean fetchDistrict) {
    Session session = SessionHelper.getCurrentSession(sessionFactory);
    Criteria criteria = session.createCriteria(Customer.class);
    if (fetchDistrict) {
      Criteria cityCriteria = criteria.createCriteria("address.city");
      Criteria regionCriteria = cityCriteria.createCriteria("region");
      regionCriteria.createCriteria("country");
    }
    criteria.add(Restrictions.idEq(id));
    List<Customer> list = criteria.list();
    if (list != null && !list.isEmpty()) {
      return list.get(0);
    }
    return null;
  }

  @Override
  public Customer getCustomer(String alias) {
    Customer customer = getCustomer(alias, null);
    return customer;
  }

  @SuppressWarnings("unchecked")
  @Override
  public Customer getCustomer(String alias, Serializable excludedId) {
    DetachedCriteria dc = buildCustomerCriteria();
    dc.add(Restrictions.eq("alias", alias));
    if (excludedId != null) {
      dc.add(Restrictions.not(Restrictions.idEq(excludedId)));
    }
    Session session = SessionHelper.getCurrentSession(sessionFactory);
    Criteria criteria = dc.getExecutableCriteria(session);
    List<Customer> list = criteria.list();
    if (list != null && !list.isEmpty()) {
      return list.get(0);
    }
    return null;
  }

  @SuppressWarnings("unchecked")
  @Override
  public List<FlatCustomerVO> getCustomers(int firstResult, int maxResults, List<Order> orders) {
    DetachedCriteria dc = buildCustomerCriteria();
    if (orders != null && !orders.isEmpty()) {
      for (Order order : orders) {
        dc.addOrder(order);
      }
    }
    dc.createAlias("address.city", "city", JoinType.INNER_JOIN);
    ProjectionList projectionList = Projections.projectionList();
    projectionList.add(Projections.id(), "id");
    projectionList.add(Projections.property("alias"), "alias");
    projectionList.add(Projections.property("firstname"), "firstname");
    projectionList.add(Projections.property("lastname"), "lastname");
    projectionList.add(Projections.property("city.name"), "city");
    projectionList.add(Projections.property("version"), "version");
    dc.setProjection(projectionList);
    dc.setResultTransformer(new AliasToBeanResultTransformer(FlatCustomerVO.class));
    Session session = SessionHelper.getCurrentSession(sessionFactory);
    Criteria criteria = dc.getExecutableCriteria(session);
    if (firstResult > 0) {
      criteria.setFirstResult(firstResult);
    }
    if (maxResults > 0) {
      criteria.setMaxResults(maxResults);
    }
    List<FlatCustomerVO> list = criteria.list();
    return list;
  }

  @Override
  public Long getCustomersCount() {
    DetachedCriteria dc = buildCustomerCriteria();
    dc.setProjection(Projections.rowCount());
    Session session = SessionHelper.getCurrentSession(sessionFactory);
    Criteria criteria = dc.getExecutableCriteria(session);
    Number totalRecords = (Number) criteria.uniqueResult();
    return totalRecords.longValue();
  }

  @Override
  public void saveCustomer(Customer customer) {
    Session session = SessionHelper.getCurrentSession(sessionFactory);
    customer.setLocked(Boolean.FALSE);
    session.save(customer);
  }

  @Override
  public void updateCustomer(Customer customer) {
    Session session = SessionHelper.getCurrentSession(sessionFactory);
    session.update(customer);
  }
}
